package com.chess.board;

import org.eclipse.swt.widgets.Display; 
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label; 
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.SWT;
/**
* Display a chess board using SWT
*/
public class SWTBoard {
	public static final int NUMBER_OF_ROWS = 8;
	public static final int NUMBER_OF_FILES = 8;
	public static Display display = new Display(); // Display is created.
	public static Shell shell = new Shell(display, SWT.SHELL_TRIM); // Top level window is created.
	public static GridLayout layout = new GridLayout();
	public static GridData data;
	public static Label square;

	private static void createSquares()
	{
		for(int i=NUMBER_OF_ROWS; i>0; i--) {
			for(int j=1; j<=NUMBER_OF_FILES; j++) {
				data = new GridData(GridData.FILL_BOTH);
				square = new Label(shell, SWT.CENTER);
				square.setBounds(shell.getClientArea());
				square.setBackground(getColor(i, j));
				square.setText("r" + i + ":c" + j);
				square.setForeground(new Color(display, 0, 0, 250)); // Text color
				// The message to display when the mouse hover above a square:
				square.setToolTipText("Row " + i + " and Column " + j);  
				square.setLayoutData(data);
			}
		}
	} 
	
	private static Color getColor(int x, int y)
	{
		if((x+y) % 2 == 0) {
			return new Color(display, 255, 255, 255); // white
		} else {
			return new Color(display, 0, 0, 0); // black
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		layout.numColumns = NUMBER_OF_FILES;
		layout.makeColumnsEqualWidth = true;
		int squareSize = 0;
		// We get the resolution of the screen. 
		int width = display.getBounds().width;
		int height = display.getBounds().height;
		if(width >= height) {
			squareSize = height / 2;
		} else {
			squareSize = width / 2;
		}
		shell.setSize(squareSize, squareSize); // Set a size for the shell/window.
		shell.setBounds(new Rectangle(squareSize / 4, squareSize / 4, squareSize, squareSize));
		shell.setLayout(layout);
		ImageData imgData = new ImageData("board.jpg");
		Image img = new Image(display, imgData, imgData);
		shell.setImage(img);          // Set an icon for the window
		shell.setText("Chess Board"); // Set a title for the window

		createSquares();

		// shell.pack();
		shell.open(); // The window is shown on the screen.
		
		// Event main loop
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		// After the application terminates, we release the OS resources. 
		display.dispose();
	}
}
